package pro.seac.twitter.web;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.ErrorHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;

@Title("twitter-xs")
@Theme(Reindeer.THEME_NAME)
public class ApplicationUI extends UI implements ViewDisplay, ErrorHandler {
	private static final long serialVersionUID = 1L;
	private VerticalLayout viewSlot;

	protected void init(VaadinRequest request) {
		setSizeFull();
		// stworz nawigatora aplikacji
		new ApplicationNavigator(this, getApplicationContext(VaadinServlet.getCurrent().getServletContext()));
		// zainstaluj obsluge bledow
		setErrorHandler(this);
		// stworz layout
		setSizeFull();
		setContent(viewSlot = new VerticalLayout());
		viewSlot.setSizeFull();
	}

	public void showView(View view) {
		ApplicationView v = (ApplicationView) view;
		viewSlot.removeAllComponents();
		viewSlot.addComponent(v);
		viewSlot.setComponentAlignment(v, Alignment.BOTTOM_CENTER);
		v.setWidth(70, Unit.PERCENTAGE);
		v.setHeight(100, Unit.PERCENTAGE);
	}

	public static void goToView(String name) {
		getCurrent().getNavigator().navigateTo(name);
	}

	private ApplicationContext getApplicationContext(ServletContext ctx) {
		return WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
	}

	@Override
	public void error(com.vaadin.server.ErrorEvent event) {
		Throwable ex = event.getThrowable();
		ex.printStackTrace();
		Notification.show("B\u0142\u0105d", "Wyst\u0105pi\u0142 b\u0142\u0105d lub brak uprawnie\u0144.", Notification.Type.ERROR_MESSAGE);
		goToView("");
	}
}
